$(document).ready(function () {
    let file = null;

    $("#filedowload").click(() => {
        downFile();
    })

    $("#fileupload").click(() =>{
        $("input[type=file]").click();
    })

    $("input[type=file]").change((e) => {
        file = e.target.files[0];
        $("#filename").val(file.name);
    });

    $("#submit").click(() => {
        uploadFile();
    });

    function uploadFile() {
        if (file == null) {
            return false;
        }
        let formData = new FormData();
        formData.append("file", file);
        $.ajax({
            type: "post",
            url: "/api/book/u/addBooksByExcel",
            cache : false,
            data : formData,
            processData : false,
            contentType : false,
            success: data => {
                if (data.success) {
                    location.href="crud";
                }else {
                    alert(data.msg);
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                const msg = xhr.responseText;
                console.log(msg);
            }
        })
    }

    function downFile(){
        let xhr = new XMLHttpRequest();
        xhr.open('POST', '/api/upload/u/getBookExcel', true);//get请求，请求地址，是否异步
        xhr.responseType = "blob";    // 返回类型blob
        xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        // let form = new FormData();
        // form.append("filename", flag + ".xlsx");
        xhr.onload = function () {// 请求完成处理函数
            if (this.status === 200) {
                let blob = this.response;// 获取返回值
                let a = document.createElement('a');
                a.download = 'data.xls';
                a.href=window.URL.createObjectURL(blob);
                a.click();
            }
        };
        // 发送ajax请求
        let param = "filename=addBook.xls";
        xhr.send(param);
    }
})